<template>
  <div class="card-out-container">
    <a-spin :spinning="spinning">
      <a-row class="mb-15">
        <a-col :span="4">
          <a-button type="primary" @click="exportTable" class="mr-10" :disabled="!queryParam.styleNo">{{ $t('common.outputExcel') }}</a-button>
          <!--<a-button type="primary" ghost @click="printTable">打印</a-button>-->
        </a-col>
        <a-col :span="20" class="full-width flex-right">
          <a-form layout="inline">
            <a-form-item :label="$t('deviceManage.waterLineNo')" >
              <a-select v-model:value="queryParam.lineNoList"  mode="multiple" :placeholder="$t('common.pleaseSelect')" allowClear show-search>
                <a-select-option v-for="item in waterList" :key="item.key" :value="item.lineNo">{{ item.lineNo }}</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item :label="$t('basicData.styleNo')"   :rules="[{ required: true, message: $t('other.selectStyleNo') }]">
              <a-select v-model:value="queryParam.styleNo" :placeholder="$t('common.pleaseSelect')" allowClear show-search :filter-option="filterOption">
                <a-select-option v-for="item in styleList" :key="item.key" :value="item.styleNo">{{ item.styleNo }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item :label="$t('basicData.staff')">
              <a-select v-model:value="queryParam.staffNoList" mode="multiple" :placeholder="$t('common.pleaseSelect')" allowClear show-search>
                <a-select-option v-for="item in employeesList" :key="item.key" :value="item.staffNo">({{ item.staffNo }}) {{ item.nickName }} </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item :label="$t('common.selectDate')">
              <a-range-picker
                v-model:value="queryParam.time" :placeholder="[$t('common.startDate'), $t('common.endDate')]" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="loadData" :disabled="!queryParam.styleNo">{{ $t('common.search') }}</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <!--<a-table rowKey="id" :loading="loading" bordered size="small" :dataSource="dataSource" :columns="columns" :scroll="{y: 'calc(100vh - 320px)'}" :pagination="false" @change="handleTableChange" :rowSelection = null :showMore="showMore" :operateMargin="true" :drag="false" storeTableName="outputStyleStaffProcess"  tableColumnsSort="outputStyleStaffProcessSort" >-->
      <a-table
        rowKey="id"
        :loading="loading"
        bordered
        size="small"
        :dataSource="dataList"
        :columns="header"
        :scroll="{ y: 'calc(100vh - 320px)' }"
        :pagination="false"
        @change="handleTableChange"
        :rowSelection="null"
        :showMore="showMore"
        :operateMargin="true"
        :drag="false"
        storeTableName="outputStyleStaffProcess"
        tableColumnsSort="outputStyleStaffProcessSort"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'other'">
            <span class="text-red"></span>{{ headGroupTitle }}
          </template>
        </template>
        <template #bodyCell="{ record , column }">
          <template v-if="column.key === 'lineNo1' && !record.lineNo1" >
            <span style="margin-right: -60%;">总计：</span>
          </template>
        </template>

      </a-table>

      <div style="display: none">
        <a-table
          id="printId"
          :loading="loading"
          bordered
          size="small"
          :dataSource="printDataList"
          :columns="printColumnsArr"
          :pagination="false"
        >
        </a-table>
      </div>
    </a-spin>
  </div>
</template>
<script>
import { ListMixinPm } from "@/mixin/listMixinPm.js";
// import { columns } from './modules/config.js'
import { cloneDeep, isEmpty } from "lodash";
import {
  filterObj,
  startTimeValue,
  endTimeValue,
  getLocalStorage,
  toLineName,
} from "@/utils";
import { mapState } from "vuex";
import { store } from "@/store";
import axios from "@/utils/request";
import printJS from "print-js";
import { message } from "ant-design-vue";
// import filterDropdown from "@/components/filterDropdown/filterDropdown.vue";

export default {
  name: "outputStyleStaffProcess",
  mixins: [ListMixinPm],
  components: {
    // filterDropdown,
  },
  data() {
    return {
      // columns: columns,
      spinning: false,
      printDataList: [],
      url: {
        list: "/api/report/get-style-staff-process-old",
        exportUrl: "/api/report/export-style-staff-process-old",
      },
      columnsArr: [],
      columnsTitleArr: [],
      printColumnsArr: [],
      queryParam: {},
      showData: false,

      headGroupTitle: "", // 款式 + 时间
      header: [], // 自定义表头
      dataList: [], //返回数据

      quantityTatol1: 0,
      quantityTatol2: 0,
      quantityTatol3: 0,
      dataSoruceLength: 0,
    };
  },
  async created() {
    await store.dispatch("getStyle");
    await store.dispatch("getWater");
    // await store.dispatch('getUser')
    await store.dispatch("getEmpl");
    this.showData = true;
  },
  computed: {
    ...mapState({
      styleList: (state) => state.normalData.styleList,
      waterList: (state) => state.normalData.waterList,
      // userList: state => state.normalData.userList,
      employeesList: (state) => state.normalData.employeesList,
    }),
  },
  methods: {
    filterOption(input, option) {
      return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    //  表头变更的搜索条件
    handleTableChange(pagination, filters, sorter) {
      /*["lineNo0", "lineNo1"].forEach((i) => {
        this.queryParam[i] = (filters || {})[i];
      });*/
      if (Object.keys(sorter).length > 0) {
        this.isorter.field = sorter.order ? toLineName(sorter.field) : "";
        this.isorter.order = sorter.order
          ? sorter.order == "ascend"
            ? "asc"
            : "desc"
          : "";
      }
      this.ipagination = Object.assign(this.ipagination, pagination);
      this.loadData();
    },
    // 表头筛选
    getQueryParams() {
      // 临时取消
      if (!this.showData) return false;
      this.getColumnsList();
      let param = cloneDeep(this.queryParam);

      if (this.queryParam.time && this.queryParam.time.length) {
        param.startProductTime = startTimeValue(this.queryParam.time[0]);
        param.endProductTime = endTimeValue(this.queryParam.time[1]);
        this.queryParam.startProductTime = startTimeValue(
          this.queryParam.time[0]
        );
        this.queryParam.endProductTime = endTimeValue(this.queryParam.time[1]);
      } else {
        param.startProductTime = null;
        param.endProductTime = null;
        this.queryParam.startProductTime = null;
        this.queryParam.endProductTime = null;
      }
      delete param.time;
      param.sortingFields = this.isorter.field ? [this.isorter] : null;
      this.queryParam.sortingFields = this.isorter.field
        ? [this.isorter]
        : null;
      // param.pageNo = this.ipagination.current
      // param.pageSize = this.ipagination.pageSize
      //表头
      this.headGroupTitle = "" + this.queryParam.styleNo;
      if (this.queryParam.time) {
        this.headGroupTitle =
          "" +
          this.queryParam.styleNo +
          " (" +
          this.queryParam.time[0] +
          " - " +
          this.queryParam.time[1] +
          ")";
      }
      if (this.queryParam.styleNo) {
        param.styleNo = [this.queryParam.styleNo];
      }
      return filterObj(param);
    },

    async printTable() {
      await this.getColumnsList();
      this.queryParam.pageNo = 1;
      this.queryParam.pageSize = 65335;
      const res = await axios.postAction(this.url.list, this.queryParam);
      if (!res.data) return;
      this.spinning = true;
      if (res) {
        this.printDataList = res.data.list;
        if (this.printDataList.length > 0) {
          setTimeout(() => {
            this.printTableData();
            this.spinning = false;
          }, 2000);
        } else {
          this.spinning = false;
        }
      }
    },
    //打印
    printTableData() {
      printJS({
        printable: "printId", // 标签元素id
        type: "html",
        documentTitle: "[款式-员工-工序]",
        style:
          "#printId{width:100%;} " +
          " #printId .ant-table-thead>tr>th, #printId .ant-table-tbody>tr>td  {border: 1px solid #bcb8b8;border-collapse: collapse;} " +
          " #printId table{border-collapse: collapse;} ",
      });
    },
    async exportTable() {
      // await this.getColumnsList()
      let param = {
        pageNo: 1,
        pageSize: 65335,
        // columns:this.columnsArr ,
        // tables:this.columnsTitleArr,
        startProductTime: this.queryParam.startProductTime,
        endProductTime: this.queryParam.endProductTime,
        // sortingFields:this.queryParam.sortingFields,
        lineNoList: this.queryParam.lineNoList,
        staffNoList: this.queryParam.staffNoList || [],
        styleNo: [this.queryParam.styleNo] || [],
        // aaaa:this.queryParam,
      };
      // console.log(param)
      // this.exportExcels(this.url.exportUrl, '产量报表-款式-员工-工序', true,param)
      this.exportExcels(
        this.url.exportUrl,
        this.queryParam.styleNo,
        true,
        param
      );
    },
    async getColumnsList() {
      let colArr = [];
      let paramsArr = [];
      let titleArr = [];
      let hangerTrackTable = getLocalStorage("outputStyleStaffProcess")
        ? getLocalStorage("outputStyleStaffProcess")
        : this.header;
      // console.log(hangerTrackTable)
      if (hangerTrackTable[0] && hangerTrackTable[0].children.length > 0) {
        hangerTrackTable[0].children.forEach((item) => {
          if (!item.disappear) {
            paramsArr.push(item.dataIndex);
            titleArr.push(item.title);
            colArr.push(item);
          }
        });
      }
      this.columnsArr = paramsArr;
      this.columnsTitleArr = titleArr;
      this.printColumnsArr = colArr;
      // console.log(colArr,titleArr,paramsArr)
    },

    loadData() {
      if (!this.url.list) {
        message.error("请设置url.list属性!");
        return;
      }
      let params = this.getQueryParams();
      // console.log(params)
      if (!params) return;
      // 查询条件
      this.loading = true;
      axios
        .postAction(this.url.list, params)
        .then((res) => {
          // console.log(res,'----款式--员工--工序------')
          if (res.success) {
            this.dataSource = res.data
              ? res.data.list
                ? res.data.list
                : Array.isArray(res.data)
                ? res.data
                : []
              : [];

            let dataSoruceLength = this.dataSource.length -2
            if (!isEmpty(this.dataSource)) {
              let headerArr = [
                { key: "other", value: "other", title: "-", children: [] },
              ];
              let tempArr = [];
              let dataListArr = [];
              this.dataSource[0].forEach((item, i) => {
                headerArr[0].children.push({
                  title: item,
                  dataIndex: "lineNo" + i,
                  key: "lineNo" + i,
                  align: "center",
                  width: 120,
                  customCell: (res, index) => {
                    if(index == dataSoruceLength && !res.lineNo0 && i ==0){
                      return {colSpan: 0 }
                    }
                    if(index == dataSoruceLength && !res.lineNo0 && i ==1){
                      return {colSpan: 2 }
                    }
                  }

                });
              });
              this.header = headerArr;
              tempArr = this.dataSource.splice(1);
              tempArr.forEach((item) => {
                let obj = {};
                item.forEach((item2, j) => {
                  const o = {};
                  o["lineNo" + j] = item2;
                  Object.assign(obj, o);
                });
                dataListArr.push(obj);
              });
              this.dataList = dataListArr;
            }
            // console.log(this.header)
            // console.log(this.dataList)
            // res.data && (this.ipagination.total = res.data.total || 0);
          }
          this.getColumnsList();
          this.loading = false;
          this.selectedRowKeys = [];
        })
        .finally(() => {
          this.loading = false;
          this.tableKey = Math.random();
        });
      if (this.storeName) {
        if (typeof this.storeName == "string") {
          store.dispatch(this.storeName);
        } else if (Array.isArray(this.storeName)) {
          this.storeName.map((i) => {
            store.dispatch(i);
          });
        }
      }
    },
  },
};
</script>
